<template>
  <div class="regulatory-page">
    <div class="return" @click="goBack">
      <Icon size="25" color="#000000" name="arrow-left" class="back" />
      <div class="title">
        <p class="text">编辑地址</p>
      </div>
    </div>
    <AddressEdit
        :area-list="areaList"
        show-delete
        show-set-default
        :area-columns-placeholder="['请选择', '请选择', '请选择']"
        :address-info="addressInfo"
        @save="onSave"
        @delete="onDelete"
        @change="onChangeDetail"
    />
  </div>
</template>

<script>
import { AddressEdit, Icon, Toast } from 'vant';
import areaList from '@/assets/area.json';
import http from "@/plugins/http";
import _ from 'lodash';

export default {
  name: "NewAddView",
  components: { Icon, AddressEdit },
  data() {
    return {
      areaList,
      addressInfo: {
        id: null,
        name: '',
        tel: '',
        province: '',
        city: '',
        district: '',
        addressDetail: '',
        isDefault: false,
        areaCode: ''
      }
    };
  },
  created() {
    const addressId = this.$route.query.id;
    if (addressId) {
      http.get(`/address/id/${addressId}`)
          .then(response => {
            const addressData = response.data;
            const areaCode = this.getAreaCode(addressData.province, addressData.city, addressData.district);
            this.addressInfo = {
              id: addressData.addressId,
              name: addressData.name,
              tel: addressData.contact,
              province: addressData.province,
              city: addressData.city,
              district: addressData.district,
              addressDetail: addressData.addressLine,
              isDefault: addressData.moRen === 1,
              areaCode
            };
          })
          .catch(error => {
            console.error("获取地址数据失败:", error);
            Toast.fail("获取地址数据失败");
          });
    }
  },
  methods: {
    goBack() {
      this.$router.go(-1);
    },
    onSave(content) {
      const payload = {
        addressId: this.addressInfo.id,
        name: content.name,
        contact: content.tel,
        province: content.province,
        city: content.city,
        district: content.county,
        addressLine: content.addressDetail,
        moRen: content.isDefault ? 1 : 0,
        userName: JSON.parse(sessionStorage.getItem('username'))
      };

      if (this.addressInfo.id) {
        // 更新地址
        http.post('/address/update', payload)
            .then(() => {
              Toast.success("地址更新成功");
              this.goBack();
            })
            .catch(error => {
              console.error("更新地址失败:", error);
              Toast.fail("地址更新失败");
            });
      } else {
        // 新增地址
        http.post('/address/insert', payload)
            .then(() => {
              Toast.success("地址添加成功");
              this.goBack();
            })
            .catch(error => {
              console.error("添加地址失败:", error);
              Toast.fail("地址添加失败");
            });
      }
    },
    onDelete() {
      if (!this.addressInfo.id) return;

      http.get(`/address/delete/${this.addressInfo.id}`)
          .then(() => {
            Toast.success("地址删除成功");
            this.goBack();
          })
          .catch(error => {
            console.error("删除地址失败:", error);
            Toast.fail("地址删除失败");
          });
    },
    onChangeDetail({ detail }) {
      this.addressInfo.addressDetail = detail;
    },
    getAreaCode(province, city, district) {
      let cityId = '';
      let districtId = '';

      _.forEach(this.areaList.city_list, (o, c) => {
        if (o === city) {
          cityId = c.substring(0, 2);
          _.forEach(this.areaList.county_list, (i, a) => {
            if (i === district) {
              districtId = a.substring(0, 2);
              if (cityId === districtId) {
                this.areaCode = a;
              }
            }
          });
        }
      });

      return this.areaCode;
    }

  }
};
</script>

<style scoped>
.regulatory-page {
  background-color: #F6F7F9;
  height: 100vh;
}

.return {
  background-color: #FAEAEA;
  padding: 15px;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
}

.back {
  position: absolute;
  left: 10px;
  text-decoration: none;
}

.text {
  margin: 0;
  color: #000000;
  font-size: 16px;
}

.title {
  display: flex;
  align-items: center;
}
</style>
